package com.healthyeating.manage.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import com.healthyeating.common.utils.DateUtils;
import com.healthyeating.common.utils.SecurityUtils;
import com.healthyeating.manage.domain.FoodType;
import com.healthyeating.manage.domain.Message;
import com.healthyeating.manage.domain.vo.FoodVo;
import com.healthyeating.manage.mapper.FoodTypeMapper;
import com.healthyeating.manage.mapper.MessageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.healthyeating.manage.mapper.FoodMapper;
import com.healthyeating.manage.domain.Food;
import com.healthyeating.manage.service.IFoodService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 食材Service业务层处理
 *
 * @author 段奇乐
 * @date 2024-12-03
 */
@Service
public class FoodServiceImpl implements IFoodService {

    @Autowired
    private FoodMapper foodMapper;

    @Autowired
    private FoodTypeMapper foodTypeMapper;

    @Autowired
    private MessageMapper messageMapper;

    /**
     * 查询食材
     *
     * @param foodId 食材主键
     * @return 食材
     */
    @Override
    public Food selectFoodByFoodId(Long foodId) {
        return foodMapper.selectFoodByFoodId(foodId);
    }

    /**
     * 查询食材列表
     *
     * @param food 食材
     * @return 食材
     */
    @Override
    public List<FoodVo> selectFoodList(Food food) {
        food.setUserId(SecurityUtils.getUserId());
        List<Food> foodList = foodMapper.selectFoodList(food);
        // 查询食材类型名称，在foods集合中添加食材类型名称
        return foodList.stream().map(foodItem -> {
            FoodVo foodVo = new FoodVo();
            BeanUtil.copyProperties(foodItem, foodVo);
            // 查询食材类型名称
            if (foodItem.getFoodType() != null) {
                FoodType foodType = foodTypeMapper.selectFoodTypeByFoodTypeId(foodItem.getFoodType());
                if (foodType != null) {
                    foodVo.setFoodTypeName(foodType.getFoodTypeName());
                }
            }
            return foodVo;
        }).collect(Collectors.toList());
    }

    /**
     * 新增食材
     *
     * @param food 食材
     * @return 结果
     */
    @Override
    @Transactional
    public int insertFood(Food food) {
        food.setCreateTime(DateUtils.getNowDate());
        food.setUserId(SecurityUtils.getUserId());
        if (food.getConsumption() == null) {
            food.setConsumption(0.0);
        }
        boolean isConsumed = isFoodConsumed(food);
        int result = foodMapper.insertFood(food);
        // 判断是否已经食用完毕
        // 如果食材未被食用完，则插入消息提醒
        if (!isConsumed) {
            // 插入私信表
            Message message = new Message();
            message.setUserId(food.getUserId());
            message.setAssociationId(food.getFoodId());
            message.setIsRead("N");
            message.setIsShow("Y");
            message.setSource("tb_food");
            messageMapper.insertMessage(message);
        }
        return result;
    }

    /**
     * 判断食材是否已经被食用完
     *
     * @param food 需要判断的食材对象
     * @return true 表示食材已被食用完, false 表示还有剩余
     */
    private boolean isFoodConsumed(Food food) {
        // 使用 BigDecimal 来处理浮点数比较，以避免精度问题
        BigDecimal consumption = BigDecimal.valueOf(food.getConsumption()).setScale(1, RoundingMode.HALF_UP);
        BigDecimal total = BigDecimal.valueOf(food.getFoodTotal()).setScale(1, RoundingMode.HALF_UP);
        // 比较食材总量和已食用量
        boolean result = consumption.compareTo(total) >= 0; // result为true表示食材已食用完，否则还有剩余
        if (result) {
            food.setStatus(1);
        } else {
            food.setStatus(0);
        }
        return result;
    }

    /**
     * 修改食材
     *
     * @param food 食材
     * @return 结果
     */
    @Override
    public int updateFood(Food food) {
        boolean isConsumed = isFoodConsumed(food);
        if (isConsumed) {
            // 修改私信状态为不可见
            Message message = messageMapper.selectMessageByAssociationIdAndSource(food.getFoodId(), "tb_food");
            if (message != null) {
                message.setIsShow("N");
                messageMapper.updateMessage(message);
            }
        }
        return foodMapper.updateFood(food);
    }

    /**
     * 批量删除食材
     *
     * @param foodIds 需要删除的食材主键
     * @return 结果
     */
    @Override
    public int deleteFoodByFoodIds(Long[] foodIds) {
        return foodMapper.deleteFoodByFoodIds(foodIds);
    }

    /**
     * 删除食材信息
     *
     * @param foodId 食材主键
     * @return 结果
     */
    @Override
    public int deleteFoodByFoodId(Long foodId) {
        return foodMapper.deleteFoodByFoodId(foodId);
    }
}
